package com.usf.jprovider.schema.model.jmodel.item;

import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlSeeAlso;

import com.usf.jprovider.constants.Constants;
import com.usf.jprovider.object.JObjectNode;
import com.usf.jprovider.object.builder.SQLBuilder;
import com.usf.jprovider.object.env.Environment;
import com.usf.jprovider.schema.AbstractObject;
import com.usf.jprovider.schema.model.jmodel.item.collection.AbstractCollection;
import com.usf.jprovider.schema.model.jmodel.item.field.AbstractField;

@XmlSeeAlso({AbstractField.class, AbstractCollection.class})
public abstract class AbstractItem extends AbstractObject {

	@XmlAttribute protected boolean check;
	@XmlAttribute protected boolean persist;
	
	protected AbstractItem() {
		super();
		check = Constants.DEFAULT_ITEM_CHECK;
		persist = Constants.DEFAULT_ITEM_PERSIST;
	}

	public boolean isCheck() {
		return check;
	}
	public boolean isPersist() {
		return persist;
	}
	
	public void create(Environment env, JObjectNode parent) throws Exception {
		JObjectNode node = parent.create(name);
		parent.addChild(node);
		_create(env, node);
	}
	public boolean check(Environment env, JObjectNode parent) throws Exception {
		JObjectNode node = parent.child(name); //TODO
		return checkNode(env, node);
	}
	public boolean checkNode(Environment env, JObjectNode node) throws Exception{
		return !check || _check(env, node);
	}
	public void persist(Environment env, JObjectNode parent, SQLBuilder builder) throws Exception {
		JObjectNode node = parent.child(name);
		persistNode(env, node, builder);
	}
	public void persistNode(Environment env, JObjectNode node, SQLBuilder builder) throws Exception {
		if(persist) _persist(env, node, builder);
	}
	
	protected abstract void _create(Environment env, JObjectNode node) throws Exception;
	protected abstract boolean _check(Environment env, JObjectNode node)  throws Exception;
	protected abstract void _persist(Environment env, JObjectNode node, SQLBuilder builder) throws Exception;
}